package com.styytech.dadabao.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.BankcardListResult;
import com.styytech.dadabao.api.requestresult.RecommendProductResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseFragment;
import com.styytech.dadabao.bean.Banner;
import com.styytech.dadabao.bean.ListData;
import com.styytech.dadabao.bean.RecommendProduct;
import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.log.LogUtil;
import com.styytech.dadabao.ui.login.LoginActivity;
import com.styytech.dadabao.ui.main.MainActivity;
import com.styytech.dadabao.ui.project.ProjectDetailsActivity;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.progressbar.RoundThread;
import com.styytech.dadabao.widge.progressbar.roundprogressbar.RoundProgressBar;
import com.styytech.dadabao.widge.viewpagers.BannerView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class HomeFragment extends BaseFragment {

    String tag = LogUtil.makeLogTag("HomeFragment");
    private View rootView;

    @ViewInject(R.id.rlyt_one)
    RelativeLayout rlyt_one;

    @ViewInject(R.id.roundProgressBar1)
    RoundProgressBar mRoundProgressBar1;
    //项目名称
    @ViewInject(R.id.tv_pro_name)
    TextView tv_pro_name;
    //预期年化收益率
    @ViewInject(R.id.tv_pro_yield)
    TextView tv_pro_yield;
    //项目期限
    @ViewInject(R.id.tv_pro_date)
    TextView tv_pro_date;
    //项目规模
    @ViewInject(R.id.tv_pro_scale)
    TextView tv_pro_scale;
    int isFirst=0;

    /*****
     * 轮播图
     **/
    @ViewInject(R.id.flyt_container)
    FrameLayout fl_viewpaper;

    /*****
     * 轮播图背景图
     **/
    @ViewInject(R.id.iv_banner)
    ImageView iv_banner;

    /*****
     * 轮播图pager
     **/
    @ViewInject(R.id.vp_viewpager)
    ViewPager vp_viewpager;


    /**
     * 本身
     */
    @ViewInject(R.id.llyt_home)
    protected LinearLayout llyt_home;

    @ViewInject(R.id.btn_pro_buy)
    private Button btn_pro_buy;

    private String search_id;
    private List<String> imgList;
    private LinkedList<Object> bannerList;
    private BannerView bannerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = super.onCreateView(inflater, container, savedInstanceState,
                R.layout.fragment_home);
        setViewPaper();
        bannerView = new BannerView(context, rootView,
                R.id.llyt_viewgroup, R.id.vp_viewpager);
        iv_banner.setVisibility(View.VISIBLE);
        vp_viewpager.setVisibility(View.GONE);
        getBannerSrc();// 获取到轮播广告图列表数据，成功后则显示banner图
        return rootView;
    }

    /**
     * 设置轮播图大小
     */
    private void setViewPaper() {
        int winWidth = CommonUtils.getWindowsWidth(getActivity());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                ConstantsCommon.getViewPaperHight(winWidth));
        fl_viewpaper.setLayoutParams(params);
    }

    /**
     * 设置轮播图视图的一些属性
     *
     * @param bannerView 轮播图对象
     */
    private void setBannerView(BannerView bannerView) {
        // 是否需要循环
        // bannerView.setLoop(true);
        // 设置是否自动轮播
        bannerView.setAutoPlay(true);
        bannerView.setAutoPlayIntervalTime(5000);
        // 是否需要小圆点默认是true
        // bannerView.setDot(false);
        /**
         * 设置轮播页的轮播点(小圆点图片)列表集接口 <br>
         * */
        bannerView.setOnAddDotView(new BannerView.IBViewSetDotView() {

            @Override
            public void setDotView(ImageView imageView, int positon,
                                   int selected) {
                LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                lparams.setMargins(5, 0, 0, 5);
                imageView.setLayoutParams(lparams);
                if (positon == selected) {
                    imageView.setBackgroundResource(R.drawable.mdot_focused);
                } else {
                    imageView
                            .setBackgroundResource(R.drawable.mdot_default);
                }
            }
        });

        /** 设置轮播页的图片列表集 */
        bannerView.setOnAddPageView(new BannerView.IBViewSetPageView() {

            @Override
            public List<Object> setPageView() {
                /** 用户自定义设置轮播页的图片列表集 */
                List<Object> pageViews = new ArrayList<Object>();
                if (imgList == null) {
                    ImageView imageView = new ImageView(context);
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    imageView.setBackgroundResource(R.drawable.banner_default);
                    pageViews.add(imageView);
                    return pageViews;
                }
                for (int i = 0; i < imgList.size(); i++) {
                    ImageView imageView = new ImageView(context);
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    // 获取网络图片(Mainfest.xml要加访问网络权限)
                    DadaApplication.showImage(imgList.get(i).toString(),
                            imageView, R.drawable.banner_default, 0, false);
                    pageViews.add(imageView);
                }
                return pageViews;
            }
        });
        /** 设置滑动到当前轮播页所需要执行的事件 */
        bannerView.setOnCurrentPageListener(new BannerView.IBViewCurrentPageListener() {

            @Override
            public void setCurrentPageEvent(Object obj, final int positioncur) {
                View view = (View) obj;
                view.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Banner banner = (Banner) bannerList.get(positioncur);
                        if ("1".equals(banner.getbType())) {//进入项目详情
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), ProjectDetailsActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("id", banner.getRecordId());
                            intent.putExtras(bundle);
                            getActivity().startActivity(intent);
                        } else if ("0".equals(banner.getbType())) {//进入项目列表
                            /// TODO 进入项目列表
                            ((MainActivity) getActivity()).gotoClass2();
                        }
                    }
                });
            }
        });

        /**
         * 显示VIEWPAGER：轮播图片，轮播小圆点，轮播标题等。
         * 所以小圆点，轮播标题应在显示VIEWPAGER前进行自定义设置，不设置则默认系统设置
         */
        try {
            bannerView.displayViewPager();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews();
    }

    private void initViews() {
        RelativeLayout.LayoutParams lparams = (RelativeLayout.LayoutParams) mRoundProgressBar1.getLayoutParams();
        //lparams.width=(int) (CommonUtils.getWindowsWidth(getActivity())*0.7);
        // lparams.height=(int) (CommonUtils.getWindowsWidth(getActivity())*0.7);
        lparams.width = (int) (CommonUtils.getWindowsHight(getActivity()) / 3);
        lparams.height = (int) (CommonUtils.getWindowsHight(getActivity()) / 3);
        mRoundProgressBar1.setLayoutParams(lparams);


        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        rlyt_one.measure(w, h);
        tv_pro_scale.measure(w, h);

        RelativeLayout.LayoutParams lparamss = (RelativeLayout.LayoutParams) mRoundProgressBar1.getLayoutParams();
        lparamss.width = (int) (rlyt_one.getMeasuredHeight() + tv_pro_scale.getMeasuredHeight() * 0.5);
        lparamss.height = (int) (rlyt_one.getMeasuredHeight() + tv_pro_scale.getMeasuredHeight() * 0.5);
        mRoundProgressBar1.setLayoutParams(lparamss);

        //缺口角度
        mRoundProgressBar1.setNotch_degree(100);

        getProjuct();
    }

    public void reloadBtnOnclick() {
        Log.i("INFO", "reloadBtnOnclick");
        getProjuct();

    }
    public void tabreloadBtnOnclick() {
        Log.i("INFO", "reloadBtnOnclick");
        getProjuct();
        getBannerSrc();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (bannerView != null) {
            bannerView.recoverPlay();
        }
    }

    //获取推荐项目
    private void getProjuct() {
        //打开等待框
        if (isFirst == 0) {
            if (llyt_home != null) {
                llyt_home.setVisibility(View.GONE);
            }
            setView(View.VISIBLE, View.VISIBLE, View.VISIBLE, View.GONE, "正在获取数据，请稍等...");
        }

        String url = ConstantsServerUrl.getRecommendProductUrl();
       /* RequestParams params = new RequestParams();
        params.put("appType", "1");
        params.put("appName", "dada");*/


        RecommendProductResult logResult = new RecommendProductResult(responseResult);
        try {
            new HttpRequest(getActivity()).doGet(logResult, url);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }

    }

    /**
     * 获取广告图片的url列表请求
     */
    private void getBannerSrc() {
        String url = ConstantsServerUrl.getBannerListUrl();

        BankcardListResult logResult = new BankcardListResult(responseResult, ConstantsCommon.DATA_SRC_BANNER);
        try {
            new HttpRequest(getActivity()).doGet(logResult, url);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }

    }

    /**
     * 请求成功，更新轮播页视图
     *
     * @param object
     */
    private void updateViews(Object object) {
        imgList = new ArrayList<String>();
        imgList.clear();
        ListData listData = (ListData) object;
        if (!listData.getDataList().isEmpty()&&  listData.getDataList().get(0) instanceof Banner) {
            bannerList = listData.getDataList();
            for (int i = 0; i < bannerList.size(); i++) {
                Banner banner = (Banner) bannerList.get(i);
                imgList.add(ConstantsServerUrl.servers + banner.getUrl());
            }
            if (imgList != null) {
                if (imgList.size() > 1) {// 如果轮播图>1张则显示轮播点
                    bannerView.setDot(true);
                }
                setBannerView(bannerView);
                iv_banner.setVisibility(View.GONE);
                vp_viewpager.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setUpViews(Object object) {
        RecommendProduct recommendProduct = (RecommendProduct) object;


        if (recommendProduct.getId()!=null&&!recommendProduct.getId().equals("")) {
            search_id = recommendProduct.getId();
        }
        if (recommendProduct.getProductName()!=null&&!recommendProduct.getProductName().equals("")) {
            tv_pro_name.setText(recommendProduct.getProductName());
        }
        if (recommendProduct.getExpectedReturnRatio()!=null&&!recommendProduct.getExpectedReturnRatio().isEmpty()) {
            double ss = Double.parseDouble(recommendProduct.getExpectedReturnRatio());
           /* TextPaint tp = tv_pro_yield.getPaint();
            tp.setFakeBoldText(true);*/
            tv_pro_yield.setText(String.format("%.2f", ss) + "%");
        }
        if (recommendProduct.getTimeLimit()!=null&&!recommendProduct.getTimeLimit().equals("")) {
            tv_pro_date.setText("项目期限" + recommendProduct.getTimeLimit() + "天");
        }
        if (recommendProduct.getTotalCredit() != 0) {
            //(int)(recommendProduct.getTotalCredit() / 10000 )+ "万元"
            tv_pro_scale.setText("项目规模" + (int) (recommendProduct.getTotalCredit() / 10000) + "万元");
        }

        if (recommendProduct.getTotalCredit() != 0 && recommendProduct.getProgress() != 0) {
            Display mDisplay = getActivity().getWindowManager().getDefaultDisplay();
            int W = mDisplay.getWidth();
            int H = mDisplay.getHeight();
            Log.e("Main", "Width = " + W);
            Log.e("Main", "Height = " + H);
            //当前百分比
            int s = (int) (((float) recommendProduct.getProgress() / (float) recommendProduct.getTotalCredit()) * 100);
            Log.e("asd", "百分比=" + s);

            /**

             *480 800  6  三星最低分辨率
             *  * 1080 1794 3  华为荣耀
             * * 720 1280 1------->OK的--大神
             *1440 2392---------》ok的  摩托罗拉
             * 1200 1830-------》OK的  华为大手机
             * */
            if(W>1000&&W<1081&&H>1790&&H<1920){
                if(s>0&&s<3){
                    RoundThread myThread = new RoundThread(3, mRoundProgressBar1);
                    myThread.start();
                }else {
                    RoundThread myThread = new RoundThread(s, mRoundProgressBar1);
                    myThread.start();
                }
            }else if (W<481){
                if(s>0&&s<6){
                    RoundThread myThread = new RoundThread(6, mRoundProgressBar1);
                    myThread.start();
                }else{
                    RoundThread myThread = new RoundThread(s, mRoundProgressBar1);
                    myThread.start();
                }
            }else{
                RoundThread myThread = new RoundThread(s, mRoundProgressBar1);
                myThread.start();
            }


        }

    }

    /**
     * 获取推荐结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {
        @Override
        public void executeSuccess(Object object) {
            if (object instanceof RecommendProduct) {
                if (isFirst == 0) {
                    if (llyt_home != null) {
                        llyt_home.setVisibility(View.VISIBLE);
                    }
                    setView(View.GONE, View.VISIBLE, View.VISIBLE, View.GONE, "正在获取数据，请稍等...");
                    isFirst = 1;
                }
                RecommendProduct recommendProduct = (RecommendProduct) object;
                if (recommendProduct.getId() == null || recommendProduct.getId().isEmpty()) {
                    setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "抱歉，暂时没有在售项目" );
                    if (llyt_home != null) {
                        llyt_home.setVisibility(View.GONE);
                    }
                    return;
                }else{
                    if (llyt_home != null) {
                        llyt_home.setVisibility(View.VISIBLE);
                    }
                }
                setUpViews(object);
            } else if (object instanceof ListData) {
                if (object == null) return;
                updateViews(object);
            }

        }

        @Override
        public void executeError(String message, int errorCode) {
            if (isFirst==0){
                CommonUtils.showToastMsg(getmActivity(), "" + message);
                setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
            }

        }

        @Override
        public void HttpError(String message, int errorCode) {
            if (isFirst==0){
                CommonUtils.showToastMsg(getmActivity(), "" + message);
                setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
            }
        }
    };

    @OnClick(R.id.btn_pro_buy)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_pro_buy:
                //立即投资
                if (SpUser.getUserToken(getActivity()) == null || SpUser.getUserToken(getActivity()).equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                   /* Intent intent=new Intent();
                    intent.setClass(getActivity(), InvestmentAmountActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("id", search_id);
                    intent.putExtras(bundle);
                    startActivity(intent);*/
                    Intent intent = new Intent();
                    intent.setClass(getmActivity(), ProjectDetailsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", search_id);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                break;
        }
    }
}
